import storage from 'good-storage'

function inertArray(arr, val, cb, maxLen) {
  const index = arr.findIndex(cb)
  if (index > -1) {
    return
  }
  arr.unshift(val)
  if (maxLen && arr.length > maxLen) {
    arr.pop()
  }
}
/**
 * @item 数据
 * @key key值
 * @cb 比较方法
 * @maxLen 最多保存多少歌曲
*/
export function save(item, key, cb, maxLen) {
  const items = storage.get(key, [])
  console.log(item, items)
  inertArray(items, item, cb, maxLen)
  storage.set(key, items)
  return items
}

export function remove(key, cb) {
  const items = storage.get(key, [])
  deleteFromArray(items, cb)
  storage.set(key, items)
  return items
}

export function load(key) {
  return storage.get(key, [])
}

function deleteFromArray(arr, cb) {
  const index = arr.findIndex(cb)
  if (index > -1) {
    arr.splice(index, 1)
  }
}
